<template>
  <div id="promotion-recommend">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <!-- 查询开始 -->
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="margin-top:20px"
          >
            <el-form-item>
              <el-select v-model="formInline.type" placeholder="请选择推荐类型">
                <el-option
                  v-for="item in optionsRecommend"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit()"
                icon="el-icon-search"
                clearable
                v-permission="'promote:recommend:query'"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit()"
                >添加</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 查询结束 -->
        </el-header>

        <el-main>
          <el-table
            :data="recommendtableData"
            style="width: 100%;"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
          >
            <!-- 列表数据 -->
            <el-table-column prop="id" label="推荐ID" sortable>
            </el-table-column>
            <el-table-column prop="spuTitle" label="推荐商品">
            </el-table-column>
            <el-table-column
              :data="recommendtableData.roleIds"
              label="推荐类型"
            >
              <template slot-scope="scope">
                <el-tag>
                  {{scope.row.recommendType|recommendType}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-permission="'promote:recommend:delete'"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <!-- 底部页数 -->
          <paging :paging="paging" :onSubmit="onSubmit"></paging>
        </el-footer>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible" center>
      <!-- 对话框表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="width:85%"
      >
        <el-form-item label="推荐类型" prop="recommendType">
          <el-select
            v-model="ruleForm.recommendType"
            placeholder="请选择推荐类型"
          >
            <el-option
              v-for="item in optionsRecommend"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推荐商品" prop="commodity">
          <el-cascader
              ref="commodity"
            v-model="ruleForm.commodity"
            :options="optionsCommodity"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 对话框表单结束 -->
    </el-dialog>
  </div>
</template>

<script>
import recommend from "@/api/recommend";
import Paging from "../../components/Paging";
export default {
  components: {
    Paging,
  },
  data() {
    var validateType = (rule, value, callback) => {
      if (value === null||value === "") {
        callback(new Error("类型不能为空"));
      } else {
        callback();
      }
    };
    var validateCommodity = (rule, value, callback) => {
      if (value === null||value[0]===null) {//第一次进入是value为null，之后都是value[0]为null
        callback(new Error("商品不能为空"));
      } else {
        callback();
      }
    };
    return {
      optionsRecommend: [
        //选项框类型
        {
          value: 0,
          label: "橱窗推荐",
        },
        {
          value: "",
          label: "全部",
        },
      ],
      optionsCommodity: "", //选项框商品
      formInline: {
        recommendType: null, //管理员查询
      },
      ruleForm: {
        //表单数据
        recommendType: null,
        commodity: null,
      },
      rules: {
        //表单验证
        recommendType: [
          { required: true, validator: validateType, trigger: "blur" },
        ],
        commodity: [
          { required: true, validator: validateCommodity, trigger: "blur" },
        ],
      },
      title: "创造", //对话框的名字
      dialogFormVisible: false, //对话框表单的隐藏显示
      recommendtableData: [], //后台全部列表数据
      paging: {
        currentPage: 1, //出现的页数
        pagesize: 10, //    每页的数据
        total: 0, //总条数
      },
    };
  },
  created: function() {
    //一开始的渲染数据
    this.onSubmit();
    recommend.recommendSPU().then((res) => {
      this.optionsCommodity =this.getTreeData(res.data.data);
    });
  },
  filters: {//过滤
    recommendType:function(value){
      switch(value)
      {
        case 1 :
          value="橱窗推荐"
        break;
        default :
          value="全部"
        break;
      }
      return value
    },
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      if (that.formInline.admin != "") {
        //具体查询回到第一页，不然查询的数据在第一页，显示的页数和查询是页数不对
        that.paging.currentPage = 1;
      }
       let data = Object.assign({}, that.formInline,that.paging);
      recommend
        .recommendInquire(
          //查询接口封装
            data
         )
        .then((res) => {
          console.log(res);
          that.recommendtableData = res.data.data.items; //获取数据赋值
          that.paging.total = res.data.data.total; //总条数
        })
        .catch(function(error) {
          console.log(error);
        });
    },
     getTreeData(data) {//递归方法
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {//children是数据库中的变量名
            data[i].children = undefined;
          } else {
            this.getTreeData(data[i].children);//返回元素的子元素的集合有数据继续导出
          }
        }
        return data;
      },
    handleEdit() {
      //添加
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
    },
    submitForm(formName) {
      //提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
            //添加
            this.addition();
        } else {
          return false;
        }
      });
    },
    addition() {
      //添加
      let that = this;
      recommend
        .recommendAdd({
          //添加封装接口
            spuId:that.$refs.commodity.getCheckedNodes()[0].data.id,
            recommendType : that.ruleForm.recommendType
          })
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.$message({
              type: "success",
              message: res.data.errmsg,
            });
            that.paging.total = that.paging.total + 1; //总共条数+1条
            that.onSubmit()
            that.recommendtableData.push(res.data.data);
          } else {
            that.$message({
              message: res.data.errmsg,
              type: "warning",
            });
          }
        });
    },
    resetForm(formName) {
      //重置验证
      let that = this;
      setTimeout(function() {
        that.$refs[formName].resetFields();
      }, 100);
    },
    handleDelete(index, row) {
      //删除
      console.log(index, row.spuTitle);
      let that = this;
      this.$confirm("此操作将永久删除--"+row.spuTitle+"--, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          recommend
            .recommendDelete({
              //删除封装接口
              id: row.id,
              recommendType: row.recommendType,
            })
            .then(function(res) {
              if (res.data.errmsg == "成功") {
                that.$message({
                  type: "success",
                  message: res.data.errmsg,
                });
                that.paging.total = that.paging.total - 1; //总共条数-1条
                that.recommendtableData.splice(index, 1);
              } else {
                that.$message({
                  showClose: true,
                  message: res.data.errmsg,
                  type: "error",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleChange(value) {
      console.log(value);
    },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#promotion-recommend {
  //内容填满
  height: 100%;
}
.el-main {
  line-height: 0px !important;
}
.concer-input {
  //查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
</style>
